<!-- 下拉加载更多 -->
<template>
  <div class="scorll-more-box" ref="container" @scroll="handleScroll">
    <slot></slot>
    <!-- 加载提示 -->
    <div class="loading" v-if="loading">
      加载中...
    </div>
    <div class="no-more" v-else-if="!hasMore">
      没有更多数据了
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoadMoreList',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    // 注意：必须使用sync修饰符来双向绑定no
    no: {
      type: Number,
      default: 1
    },
    size: {
      type: Number,
      default: 50
    },
    total: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      isLocked: false, // 上锁
    }
  },
  computed: {
    hasMore() {
      return this.total === 0 || this.no * this.size <= this.total;
    }
  },
  methods: {
    async loadMore() {
      if (this.loading || !this.hasMore || this.isLocked) return

      this.isLocked = true // 加锁防止频繁触发

      this.$emit('update:no', this.no + 1);
      this.$emit('getData');

      setTimeout(() => {
        this.isLocked = false;
      }, 500); // 0.5秒后解锁，注：如果每页数据太少，有滚动很快，可能会卡住哦
    },

    handleScroll() {
      const el = this.$refs.container
      // 判断是否滚动到底部（留 10px 缓冲）
      if (el.scrollHeight - el.scrollTop - el.clientHeight < 10) {
        this.loadMore()
      }
    }
  }
}
</script>

<style scoped>
.scorll-more-box {
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
  scrollbar-gutter: stable;
}

.loading, .no-more {
  text-align: center;
  padding: 10px;
  color: var(--color-text-65);
}
</style>